import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { Water } from 'three/examples/jsm/objects/Water';
import { Sky } from 'three/examples/jsm/objects/Sky';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
import styles from './GuangaiDongtai.module.less';

const GuangaiDongtai: React.FC = () => {
  const containerRef = useRef<HTMLDivElement>(null);
  const sceneRef = useRef<THREE.Scene | null>(null);
  const waterRef = useRef<Water | null>(null);
  const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
  const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
  const controlsRef = useRef<OrbitControls | null>(null);
  const animationRef = useRef<number | null>(null);
  
  // 初始化场景
  const initScene = () => {
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x87CEEB);
    scene.fog = new THREE.FogExp2(0xefd1b5, 0.0008);
    sceneRef.current = scene;
    return scene;
  };

  // 初始化相机
  const initCamera = (container: HTMLDivElement) => {
    const camera = new THREE.PerspectiveCamera(
      55,
      container.clientWidth / container.clientHeight,
      0.1,
      2000
    );
    camera.position.set(180, 120, 180);
    camera.lookAt(0, 50, 0);
    cameraRef.current = camera;
    return camera;
  };

  // 初始化渲染器
  const initRenderer = (container: HTMLDivElement) => {
    const renderer = new THREE.WebGLRenderer({ 
      antialias: true,
      alpha: false,
      powerPreference: "high-performance"
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(container.clientWidth, container.clientHeight);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    renderer.toneMapping = THREE.ACESFilmicToneMapping;
    renderer.toneMappingExposure = 0.85;
    renderer.outputEncoding = THREE.sRGBEncoding;
    container.appendChild(renderer.domElement);
    rendererRef.current = renderer;
    return renderer;
  };

  // 初始化控制器
  const initControls = (camera: THREE.PerspectiveCamera, renderer: THREE.WebGLRenderer) => {
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.maxPolarAngle = Math.PI * 0.45;
    controls.minDistance = 50;
    controls.maxDistance = 500;
    controlsRef.current = controls;
    return controls;
  };

  // 初始化天空
  const initSky = (scene: THREE.Scene) => {
    const sky = new Sky();
    sky.scale.setScalar(10000);
    scene.add(sky);

    const skyUniforms = sky.material.uniforms;
    skyUniforms['turbidity'].value = 10;
    skyUniforms['rayleigh'].value = 2;
    skyUniforms['mieCoefficient'].value = 0.005;
    skyUniforms['mieDirectionalG'].value = 0.8;
    skyUniforms['sunPosition'].value = new THREE.Vector3(100, 100, 50);
    
    return sky;
  };

  // 初始化环境光
  const initEnvironment = (scene: THREE.Scene) => {
    new RGBELoader()
      .load('/textures/industrial_sunset_puresky_1k.hdr', (texture) => {
        texture.mapping = THREE.EquirectangularReflectionMapping;
        scene.environment = texture;
        scene.background = texture;
      });
  };

  // 创建地形
  const createTerrain = (scene: THREE.Scene) => {
    const geometry = new THREE.PlaneGeometry(1000, 1000, 256, 256);
    const textureLoader = new THREE.TextureLoader();
    const grassTexture = textureLoader.load('/textures/terrain/grass.jpg');
    grassTexture.wrapS = grassTexture.wrapT = THREE.RepeatWrapping;
    grassTexture.repeat.set(20, 20);

    // 地形高度和颜色计算
    const vertices = geometry.attributes.position.array;
    const colors = [];
    const color = new THREE.Color();
    
    for (let i = 0; i < vertices.length; i += 3) {
      const x = vertices[i];
      const z = vertices[i + 2];
      const noise1 = Math.sin(x * 0.01) * 15;
      const noise2 = Math.cos(z * 0.015) * 12;
      const noise3 = Math.sin(x * 0.03 + z * 0.02) * 8;
      const distanceFromCenter = Math.sqrt(x * x + z * z);
      
      if (distanceFromCenter < 120) {
        const depthFactor = 1 - (distanceFromCenter / 120);
        vertices[i + 1] = (noise1 + noise2 + noise3) - Math.pow(depthFactor * 2, 3) * 50;
      } else {
        vertices[i + 1] = noise1 + noise2 + noise3;
      }
      
      vertices[i + 1] += (Math.random() - 0.5) * 3;
      
      // 根据高度设置颜色
      const elevation = vertices[i + 1];
      if (elevation < 10) {
        color.setHex(0x91B496);
      } else if (elevation < 30) {
        color.setHex(0xA3B86C);
      } else {
        color.setHex(0x8A9A5B);
      }
      colors.push(color.r, color.g, color.b);
    }
    
    geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
    
    const material = new THREE.MeshStandardMaterial({
      map: grassTexture,
      color: 0x91B496,
      side: THREE.DoubleSide,
      vertexColors: true,
      roughness: 0.8,
      metalness: 0.2,
      bumpMap: grassTexture,
      bumpScale: 0.5
    });

    const terrain = new THREE.Mesh(geometry, material);
    terrain.rotation.x = -Math.PI / 2;
    terrain.receiveShadow = true;
    terrain.castShadow = true;
    scene.add(terrain);
    
    // 添加岩石细节
    addRocks(scene);
  };

  // 添加岩石细节
  const addRocks = (scene: THREE.Scene) => {
    const rockGeometry = new THREE.SphereGeometry(1, 6, 6);
    const textureLoader = new THREE.TextureLoader();
    const rockTexture = textureLoader.load('/textures/terrain/rock.jpg');
    const rockMaterial = new THREE.MeshStandardMaterial({
      map: rockTexture,
      roughness: 0.9,
      metalness: 0.1
    });
    
    for (let i = 0; i < 500; i++) {
      const rock = new THREE.Mesh(rockGeometry, rockMaterial);
      const angle = Math.random() * Math.PI * 2;
      const radius = 100 + Math.random() * 400;
      rock.position.set(
        Math.cos(angle) * radius,
        -1 + Math.random() * 2,
        Math.sin(angle) * radius
      );
      rock.scale.setScalar(0.5 + Math.random() * 2);
      rock.rotation.set(
        Math.random() * Math.PI,
        Math.random() * Math.PI,
        Math.random() * Math.PI
      );
      scene.add(rock);
    }
  };

  // 创建水坝
  const createDam = (scene: THREE.Scene) => {
    const textureLoader = new THREE.TextureLoader();
    const concreteTexture = textureLoader.load('/textures/concrete.jpg');
    concreteTexture.wrapS = concreteTexture.wrapT = THREE.RepeatWrapping;
    concreteTexture.repeat.set(4, 2);
    
    // 主坝体
    const damGeometry = new THREE.BoxGeometry(120, 80, 10);
    const damMaterial = new THREE.MeshStandardMaterial({ 
      map: concreteTexture,
      roughness: 0.7,
      metalness: 0.1,
      bumpMap: concreteTexture,
      bumpScale: 0.2
    });
    
    const dam = new THREE.Mesh(damGeometry, damMaterial);
    dam.position.set(0, 40, 0);
    dam.castShadow = true;
    dam.receiveShadow = true;
    scene.add(dam);

    // 溢洪道
    createSpillway(scene);
    
    // 控制室
    createControlHouse(scene);
    
    // 水流效果
    createWaterFlow(scene);
  };

  // 创建溢洪道
  const createSpillway = (scene: THREE.Scene) => {
    const textureLoader = new THREE.TextureLoader();
    const metalTexture = textureLoader.load('/textures/metal.jpg');
    metalTexture.wrapS = metalTexture.wrapT = THREE.RepeatWrapping;
    metalTexture.repeat.set(1, 2);
    
    for (let i = 0; i < 12; i++) {
      const spillwayGeometry = new THREE.BoxGeometry(8, 60, 2);
      const spillwayMaterial = new THREE.MeshStandardMaterial({
        map: metalTexture,
        roughness: 0.4,
        metalness: 0.8
      });
      
      const spillway = new THREE.Mesh(spillwayGeometry, spillwayMaterial);
      spillway.position.set(-44 + i * 8, 30, 5);
      spillway.castShadow = true;
      scene.add(spillway);

      // 溢洪道装饰
      const decorGeometry = new THREE.BoxGeometry(6, 5, 4);
      const decorMaterial = new THREE.MeshStandardMaterial({
        color: 0xCCCCCC,
        roughness: 0.3,
        metalness: 0.9
      });
      
      const decor = new THREE.Mesh(decorGeometry, decorMaterial);
      decor.position.set(-44 + i * 8, 65, 5);
      decor.castShadow = true;
      scene.add(decor);
    }
  };

  // 创建控制室
  const createControlHouse = (scene: THREE.Scene) => {
    const houseGeometry = new THREE.BoxGeometry(20, 15, 15);
    const houseMaterial = new THREE.MeshStandardMaterial({
      color: 0xE0E0E0,
      roughness: 0.6
    });
    
    const house = new THREE.Mesh(houseGeometry, houseMaterial);
    house.position.set(0, 77.5, 0);
    house.castShadow = true;
    scene.add(house);
    
    // 屋顶
    const roofGeometry = new THREE.ConeGeometry(12, 5, 4);
    const roofMaterial = new THREE.MeshStandardMaterial({
      color: 0x8B0000,
      roughness: 0.8
    });
    
    const roof = new THREE.Mesh(roofGeometry, roofMaterial);
    roof.position.set(0, 85, 0);
    roof.rotation.y = Math.PI / 4;
    roof.castShadow = true;
    scene.add(roof);
  };

  // 创建水流效果
  const createWaterFlow = (scene: THREE.Scene) => {
    const flowGeometry = new THREE.PlaneGeometry(100, 40);
    const flowMaterial = new THREE.MeshStandardMaterial({
      color: 0x4F94CD,
      transparent: true,
      opacity: 0.7,
      roughness: 0.1,
      metalness: 0.3
    });
    
    const flow = new THREE.Mesh(flowGeometry, flowMaterial);
    flow.rotation.x = -Math.PI / 3;
    flow.position.set(0, 20, 10);
    scene.add(flow);
    
    // 水花粒子
    createWaterSplashes(scene);
  };

  // 创建水花粒子
  const createWaterSplashes = (scene: THREE.Scene) => {
    const particleCount = 500;
    const particles = new THREE.BufferGeometry();
    const posArray = new Float32Array(particleCount * 3);
    
    for (let i = 0; i < particleCount * 3; i++) {
      posArray[i] = (Math.random() - 0.5) * 100;
      if (i % 3 === 1) posArray[i] = Math.random() * 40;
    }
    
    particles.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
    
    const particleMaterial = new THREE.PointsMaterial({
      size: 0.5,
      color: 0x4F94CD,
      transparent: true,
      opacity: 0.8,
      sizeAttenuation: true
    });
    
    const particleSystem = new THREE.Points(particles, particleMaterial);
    particleSystem.position.set(0, 20, 10);
    scene.add(particleSystem);
  };

  // 创建水面
  const createWater = (scene: THREE.Scene) => {
    const waterGeometry = new THREE.CircleGeometry(150, 64);
    
    const water = new Water(waterGeometry, {
      textureWidth: 1024,
      textureHeight: 1024,
      waterNormals: new THREE.TextureLoader().load(
        '/textures/waternormals.jpg',
        (texture) => {
          texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
        }
      ),
      sunDirection: new THREE.Vector3(100, 100, 50).normalize(),
      sunColor: 0xffffff,
      waterColor: 0x4F94CD,
      distortionScale: 4.0,
      fog: scene.fog !== undefined
    });
    
    water.rotation.x = -Math.PI / 2;
    water.position.y = 60;
    water.position.z = -70;
    water.receiveShadow = true;
    scene.add(water);
    waterRef.current = water;
    
    // 水下地形
    createUnderwaterTerrain(scene);
  };

  // 创建水下地形
  const createUnderwaterTerrain = (scene: THREE.Scene) => {
    const underwaterGeometry = new THREE.SphereGeometry(140, 32, 32, 0, Math.PI * 2, 0, Math.PI * 0.5);
    const underwaterMaterial = new THREE.MeshStandardMaterial({
      color: 0x3A5F0B,
      roughness: 0.9,
      side: THREE.BackSide,
      transparent: true,
      opacity: 0.7
    });
    
    const underwater = new THREE.Mesh(underwaterGeometry, underwaterMaterial);
    underwater.position.y = 30;
    underwater.position.z = -70;
    underwater.rotation.x = Math.PI / 2;
    scene.add(underwater);
  };

  // 创建山脉
  const createMountains = (scene: THREE.Scene) => {
    const mountainGeometry = new THREE.ConeGeometry(50, 100, 32);
    const mountainMaterial = new THREE.MeshStandardMaterial({
      color: 0x6B8E23,
      roughness: 0.9,
      metalness: 0.1
    });

    const mountainPositions = [
      [-100, 50, -150],
      [100, 60, -180],
      [-150, 70, -100],
      [150, 55, -120],
      [-200, 80, -50],
      [200, 65, -70]
    ];

    mountainPositions.forEach(pos => {
      const mountain = new THREE.Mesh(mountainGeometry, mountainMaterial);
      mountain.position.set(pos[0], pos[1], pos[2]);
      mountain.rotation.y = Math.random() * Math.PI;
      mountain.castShadow = true;
      mountain.receiveShadow = true;
      mountain.scale.x = 1 + Math.random() * 0.5;
      mountain.scale.z = 1 + Math.random() * 0.5;
      scene.add(mountain);
    });
    
    // 添加树木
    addTrees(scene);
  };

  // 添加树木
  const addTrees = (scene: THREE.Scene) => {
    const treeGeometry = new THREE.ConeGeometry(3, 10, 8);
    const treeTrunkGeometry = new THREE.CylinderGeometry(0.5, 0.8, 2);
    
    const treeMaterial = new THREE.MeshStandardMaterial({ color: 0x2E8B57 });
    const trunkMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513 });
    
    for (let i = 0; i < 100; i++) {
      const angle = Math.random() * Math.PI * 2;
      const radius = 150 + Math.random() * 200;
      const height = 30 + Math.random() * 50;
      
      const trunk = new THREE.Mesh(treeTrunkGeometry, trunkMaterial);
      trunk.position.set(
        Math.cos(angle) * radius,
        height,
        Math.sin(angle) * radius
      );
      trunk.castShadow = true;
      scene.add(trunk);
      
      const tree = new THREE.Mesh(treeGeometry, treeMaterial);
      tree.position.set(
        Math.cos(angle) * radius,
        height + 6,
        Math.sin(angle) * radius
      );
      tree.castShadow = true;
      scene.add(tree);
    }
  };

  // 创建灌溉渠道
  const createCanals = (scene: THREE.Scene) => {
    const canalGeometry = new THREE.BoxGeometry(300, 2, 10);
    const canalMaterial = new THREE.MeshStandardMaterial({
      color: 0x4682B4,
      roughness: 0.7,
      metalness: 0.1
    });
    
    // 主渠道
    const mainCanal = new THREE.Mesh(canalGeometry, canalMaterial);
    mainCanal.position.set(0, 61, 100);
    mainCanal.rotation.z = -0.1;
    scene.add(mainCanal);
    
    // 分支渠道
    for (let i = 0; i < 5; i++) {
      const branchGeometry = new THREE.BoxGeometry(100, 2, 8);
      const branch = new THREE.Mesh(branchGeometry, canalMaterial);
      branch.position.set(-120 + i * 60, 60 + i * 0.5, 150);
      branch.rotation.z = -0.05;
      scene.add(branch);
    }
    
    // 渠道水流
    const flowGeometry = new THREE.PlaneGeometry(300, 8);
    const flowMaterial = new THREE.MeshStandardMaterial({
      color: 0x4F94CD,
      transparent: true,
      opacity: 0.8,
      roughness: 0.1
    });
    
    const flow = new THREE.Mesh(flowGeometry, flowMaterial);
    flow.position.set(0, 62, 100);
    flow.rotation.x = -Math.PI / 2 + 0.1;
    scene.add(flow);
  };

  // 创建农田
  const createFarmland = (scene: THREE.Scene) => {
    const fieldGeometry = new THREE.PlaneGeometry(80, 80);
    const fieldMaterial = new THREE.MeshStandardMaterial({
      color: 0x7CFC00,
      roughness: 0.9
    });
    
    // 网格状农田
    for (let x = -3; x <= 3; x++) {
      for (let z = 2; z <= 5; z++) {
        const field = new THREE.Mesh(fieldGeometry, fieldMaterial);
        field.position.set(x * 90, 60.1, z * 80 + 50);
        field.rotation.x = -Math.PI / 2;
        scene.add(field);
        
        // 农作物
        addCrops(scene, x * 90, z * 80 + 50);
      }
    }
  };

  // 添加农作物
  const addCrops = (scene: THREE.Scene, x: number, z: number) => {
    const cropGeometry = new THREE.BoxGeometry(1, 3, 1);
    const cropMaterial = new THREE.MeshStandardMaterial({ color: 0x32CD32 });
    
    for (let i = 0; i < 50; i++) {
      const crop = new THREE.Mesh(cropGeometry, cropMaterial);
      crop.position.set(
        x + (Math.random() - 0.5) * 70,
        61.5,
        z + (Math.random() - 0.5) * 70
      );
      scene.add(crop);
    }
  };

  // 创建信息面板
  const createInfoPanel = (container: HTMLDivElement) => {
    const div = document.createElement('div');
    div.className = styles.infoPanel;
    div.innerHTML = `
      <div class="${styles.panelContent}">
        <h3>水库监测系统</h3>
        <div class="${styles.dataRow}">
          <span class="${styles.label}">水位高度:</span>
          <span class="${styles.value}" id="waterLevel">53.2m</span>
        </div>
        <div class="${styles.dataRow}">
          <span class="${styles.label}">蓄水总量:</span>
          <span class="${styles.value}" id="waterVolume">1200万m³</span>
        </div>
        <div class="${styles.dataRow}">
          <span class="${styles.label}">当前流量:</span>
          <span class="${styles.value}" id="flowRate">12m³/s</span>
        </div>
        <div class="${styles.dataRow}">
          <span class="${styles.label}">水质指数:</span>
          <span class="${styles.value}" id="waterQuality">92.5</span>
        </div>
      </div>
    `;
    container.appendChild(div);
    
    // 动画数值
    animatePanelValues();
  };

  // 面板数值动画
  const animatePanelValues = () => {
    let time = 0;
    const animate = () => {
      time += 0.01;
      const levelElement = document.getElementById('waterLevel');
      const volumeElement = document.getElementById('waterVolume');
      const flowElement = document.getElementById('flowRate');
      const qualityElement = document.getElementById('waterQuality');
      
      if (levelElement && volumeElement && flowElement && qualityElement) {
        const level = 53.2 + Math.sin(time) * 0.2;
        const volume = 1200 + Math.sin(time * 0.5) * 5;
        const flow = 12 + Math.sin(time * 2) * 2;
        const quality = 92.5 + Math.sin(time * 0.3) * 0.5;
        
        levelElement.textContent = `${level.toFixed(1)}m`;
        volumeElement.textContent = `${volume.toFixed(0)}万m³`;
        flowElement.textContent = `${flow.toFixed(1)}m³/s`;
        qualityElement.textContent = `${quality.toFixed(1)}`;
      }
      
      requestAnimationFrame(animate);
    };
    
    animate();
  };

  // 设置光照
  const setupLights = (scene: THREE.Scene) => {
    // 环境光
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
    scene.add(ambientLight);

    // 主光源(太阳)
    const directionalLight = new THREE.DirectionalLight(0xfff4e6, 1.0);
    directionalLight.position.set(100, 200, 100);
    directionalLight.castShadow = true;
    directionalLight.shadow.mapSize.width = 2048;
    directionalLight.shadow.mapSize.height = 2048;
    directionalLight.shadow.camera.near = 0.5;
    directionalLight.shadow.camera.far = 500;
    directionalLight.shadow.camera.left = -100;
    directionalLight.shadow.camera.right = 100;
    directionalLight.shadow.camera.top = 100;
    directionalLight.shadow.camera.bottom = -100;
    scene.add(directionalLight);

    // 补光
    const fillLight = new THREE.DirectionalLight(0x667788, 0.5);
    fillLight.position.set(-100, 100, -100);
    scene.add(fillLight);
    
    // 点光源
    const damLight = new THREE.PointLight(0x4F94CD, 0.8, 50);
    damLight.position.set(0, 70, 0);
    scene.add(damLight);
    
    const waterLight = new THREE.PointLight(0x4F94CD, 0.5, 100);
    waterLight.position.set(0, 60, -70);
    scene.add(waterLight);
  };

  // 添加鸟类
  const addBirds = (scene: THREE.Scene) => {
    const birdGeometry = new THREE.BoxGeometry(1, 1, 3);
    const birdMaterial = new THREE.MeshStandardMaterial({ color: 0x333333 });
    
    const birds = [];
    for (let i = 0; i < 10; i++) {
      const bird = new THREE.Mesh(birdGeometry, birdMaterial);
      bird.position.set(
        Math.random() * 400 - 200,
        150 + Math.random() * 50,
        Math.random() * 400 - 200
      );
      bird.userData.speed = 0.5 + Math.random();
      bird.userData.angle = Math.random() * Math.PI * 2;
      scene.add(bird);
      birds.push(bird);
    }
    
    return birds;
  };

  // 初始化场景内容
  const initSceneContent = (scene: THREE.Scene, container: HTMLDivElement) => {
    createTerrain(scene);
    createDam(scene);
    createWater(scene);
    createMountains(scene);
    createCanals(scene);
    createFarmland(scene);
    createInfoPanel(container);
    setupLights(scene);
    return addBirds(scene);
  };

  // 动画循环
  const startAnimation = (
    scene: THREE.Scene, 
    camera: THREE.PerspectiveCamera, 
    renderer: THREE.WebGLRenderer,
    birds: THREE.Mesh[]
  ) => {
    const clock = new THREE.Clock();
    
    const animate = () => {
      animationRef.current = requestAnimationFrame(animate);

      const delta = clock.getDelta();
      const time = clock.getElapsedTime();
      
      // 更新水面动画
      if (waterRef.current?.material.uniforms) {
        waterRef.current.material.uniforms['time'].value += delta;
      }
      
      // 更新鸟类动画
      updateBirds(birds, delta, time);
      
      // 更新太阳位置
      updateSunPosition(scene, time);

      controlsRef.current?.update();
      renderer.render(scene, camera);
    };
    
    animate();
  };

  // 更新鸟类位置
  const updateBirds = (birds: THREE.Mesh[], delta: number, time: number) => {
    birds.forEach(bird => {
      bird.userData.angle += delta * 0.2;
      bird.position.x += Math.cos(bird.userData.angle) * bird.userData.speed;
      bird.position.z += Math.sin(bird.userData.angle) * bird.userData.speed;
      bird.position.y += Math.sin(time * 2) * 0.1;
      
      // 边界检查
      if (bird.position.length() > 300) {
        bird.position.set(
          Math.random() * 200 - 100,
          150 + Math.random() * 50,
          Math.random() * 200 - 100
        );
        bird.userData.angle = Math.random() * Math.PI * 2;
      }
    });
  };

  // 更新太阳位置
  const updateSunPosition = (scene: THREE.Scene, time: number) => {
    const skyUniforms = scene.children.find(
      child => child instanceof Sky
    )?.material.uniforms;
    
    if (skyUniforms) {
      const sunPosition = new THREE.Vector3(
        Math.cos(time * 0.1) * 100,
        Math.sin(time * 0.1) * 100 + 100,
        Math.sin(time * 0.1) * 100
      );
      skyUniforms['sunPosition'].value.copy(sunPosition);
      
      // 更新主光源位置
      const directionalLight = scene.children.find(
        child => child instanceof THREE.DirectionalLight && child.intensity > 0.9
      ) as THREE.DirectionalLight;
      
      if (directionalLight) {
        directionalLight.position.copy(sunPosition);
      }
    }
  };

  // 处理窗口大小变化
  const setupResizeHandler = (camera: THREE.PerspectiveCamera, renderer: THREE.WebGLRenderer) => {
    const handleResize = () => {
      if (!containerRef.current) return;
      
      camera.aspect = containerRef.current.clientWidth / containerRef.current.clientHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(containerRef.current.clientWidth, containerRef.current.clientHeight);
    };
    
    window.addEventListener('resize', handleResize);
    return handleResize;
  };

  // 清理资源
  const cleanup = (handleResize: () => void) => {
    window.removeEventListener('resize', handleResize);
    if (animationRef.current) {
      cancelAnimationFrame(animationRef.current);
    }
    if (containerRef.current && rendererRef.current) {
      containerRef.current.removeChild(rendererRef.current.domElement);
    }
    rendererRef.current?.dispose();
  };

  useEffect(() => {
    if (!containerRef.current) return;

    // 初始化Three.js核心组件
    const scene = initScene();
    const camera = initCamera(containerRef.current);
    const renderer = initRenderer(containerRef.current);
    initControls(camera, renderer);
    initSky(scene);
    initEnvironment(scene);

    // 初始化场景内容
    const birds = initSceneContent(scene, containerRef.current);

    // 设置动画和事件监听
    const handleResize = setupResizeHandler(camera, renderer);
    startAnimation(scene, camera, renderer, birds);

    // 清理函数
    return () => cleanup(handleResize);
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.scene} ref={containerRef}></div>
    </div>
  );
};

export default GuangaiDongtai;